<!-- 搜索文章页面 -->
<template>
  <div>
    <!-- 搜索栏 -->
    <form action="/">
      <van-search
        v-model="searchVal"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch(searchVal)"
        @cancel="$router.back()"
        @focus="isShowResult = false"
      />
    </form>

    <!-- 搜索结果 -->
    <search-result
      class="search-result"
      :search-val="searchVal"
      v-if="isShowResult"
    />

    <!-- 自动联想 -->
    <search-suggest
      v-else-if="searchVal"
      @search="onSearch"
      :search-val="searchVal"
    />

    <!-- 搜索历史 -->
    <search-record @search="onSearch" v-else :SearchRecords="SearchRecords" />
  </div>
</template>

<script>
import SearchSuggest from "./components/searchSuggest.vue";
import SearchRecord from "./components/searchRecord.vue";
import SearchResult from "./components/searchResult.vue";
import { getItem, setItem } from "../../utils/storage";
import { mapState } from "vuex";

export default {
  name: "SearchIndex",
  data() {
    return {
      searchVal: "",
      isShowResult: false,
      SearchRecords: getItem("SearchRecords") || [],
    };
  },
  created() {
    console.log(this.userInfo);
  },
  methods: {
    // 触发搜索
    onSearch(val) {
      // 让输入框设置为搜索的文本
      this.searchVal = val.trim();
      if (!val) {
        this.$toast.fail("搜索内容为空");
        return;
      }

      // 添加搜索记录
      const index = this.SearchRecords.indexOf(val);
      if (index != -1) this.SearchRecords.splice(index, 1);
      this.SearchRecords.unshift(val);
      // 持久化存储
      setItem("SearchRecords", this.SearchRecords);
      // 展示搜索结果
      this.isShowResult = true;
    },
  },
  computed: {
    ...mapState(["userInfo"]),
  },
  components: {
    SearchSuggest,
    SearchRecord,
    SearchResult,
  },
};
</script>

<style lang= "less" scoped>
.search-result {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  top: 55px;
  overflow: auto;
}
</style>